package is.ru.honn.rumblr.service;

import is.ru.honn.rumblr.data.PostDataGateway;
import is.ru.honn.rumblr.domain.AbstractRumblrPost;
import is.ru.honn.rumblr.domain.RumblrPost;
import is.ru.honn.rumblr.domain.User;
import is.ruframework.data.RuDataAccessFactory;
import is.ruframework.domain.RuException;

import java.util.Collection;

/**
 * @author Stefan Gunnarsson
 * @Version 0.1 aplha
 */
public class PostDataService implements PostService
{
    private PostDataGateway postDataGateway = null;
    protected StatisticsStrategy statisticsStrategy;
    RuDataAccessFactory factory = null;
    protected User user;

    //Creates a new dataaccess so we can access the database.
    public PostDataService() throws RuException
    {

        try
        {
            factory = RuDataAccessFactory.getInstance("data.xml");
        }
        catch (Exception ex)
        {
            throw new RuException("lol");
        }
        postDataGateway = (PostDataGateway)factory.getDataAccess("postDataGateway");
    }

    //
    public User getUser(String username)
    {
         return user;
    }

    //Sets the user to the input:user
    public void setUser(User user)
    {
        this.user = user;
    }

    //Adds a post to the database, uses postDataGateway to do so.
    public void addPost(RumblrPost post)
    {

        postDataGateway.addPost((AbstractRumblrPost) post, user.getUsername());
        statisticsStrategy.count((AbstractRumblrPost)post);
    }
    //Returns all the posts from a specific user, uses a function in postDataGateway
    public Collection<RumblrPost> getPosts(String username)
    {
        //PostData postData= new PostData();
        Collection<RumblrPost> collection;
        collection = postDataGateway.getPosts(username);
        return collection;

    }

    //Simple set function for StatisticsStrategy
    public void setStatisticsStrategy(StatisticsStrategy stats)
    {
        this.statisticsStrategy = stats;
    }

     public void printSummary()
     {
        System.out.println(statisticsStrategy.getSummary());
     }
}
